package com.xbq.oauth.controller;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@RestController
public class BrowserSecurityController {

    //使用SpringSecurity提供的请求缓存来获取当前请求信息
    private RequestCache requestCache = new HttpSessionRequestCache();

    //使用SpringSecurity提供的重定向工具
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    /**
     * 当需要身份认证时，跳转到这里
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED) //返回401状态吗
    public String requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取当前请求的上一次请求
        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if(savedRequest != null){
            String targetUrl = savedRequest.getRedirectUrl();
            log.info("引发跳转的请求是：{}" , targetUrl);

            //判断引发跳转的请求是否以.html结尾
            if(StringUtils.endsWithIgnoreCase(targetUrl,".html")){
                //如果是以.html引发的跳转，那就跳转到登陆页
                redirectStrategy.sendRedirect(request,response,"/mylogin.html");
            }
        }

        return "访问的服务需要身份认证";
    }

}
